import base64
import hashlib
import json
import os
import platform
import psutil
import requests
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import uuid
from cryptography.fernet import Fernet
from PIL import Image
import re
from datetime import datetime, timedelta
import urllib.parse
from datetime import datetime, timedelta

# OCR 应用
API_KEY = "YLOtSqjT6U6rZOmCUk466hAB"
SECRET_KEY = "ukICHsUhKDyoZ34neD06k4XwISKnV5AB"

class OCRApp:
    def __init__(self, root):
        self.root = root
        
        # 初始化主界面
        self.init_main_interface()
    
    def init_main_interface(self):
        self.root.title("图片文字识别重命名")
        self.center_window(800, 600)
        
        self.input_dir = tk.StringVar()
        self.output_dir = tk.StringVar()
        self.progress_var = tk.DoubleVar()
        self.status_var = tk.StringVar(value="准备就绪")
        self.preserve_original = tk.BooleanVar(value=False)
        
        # 创建控件
        self.create_widgets()
    
    def center_window(self, width, height):
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width - width) // 2
        y = (screen_height - height) // 2
        self.root.geometry(f"{width}x{height}+{x}+{y}")
    
    def create_widgets(self):
        ttk.Label(self.root, text="图片目录:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        ttk.Entry(self.root, textvariable=self.input_dir, width=50).grid(row=0, column=1, padx=5, pady=5)
        ttk.Button(self.root, text="浏览...", command=self.browse_input).grid(row=0, column=2, padx=5, pady=5)
        
        ttk.Label(self.root, text="输出目录:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        ttk.Entry(self.root, textvariable=self.output_dir, width=50).grid(row=1, column=1, padx=5, pady=5)
        ttk.Button(self.root, text="浏览...", command=self.browse_output).grid(row=1, column=2, padx=5, pady=5)
        
        ttk.Checkbutton(self.root, text="保留原始文件", variable=self.preserve_original).grid(row=2, column=1, sticky="w")
        ttk.Button(self.root, text="开始重命名", command=self.process_images).grid(row=3, column=1, pady=10)
        
        ttk.Label(self.root, text="进度:").grid(row=4, column=0, padx=5, pady=5, sticky="e")
        ttk.Progressbar(self.root, variable=self.progress_var, maximum=100).grid(row=4, column=1, padx=5, pady=5, sticky="ew")
        
        ttk.Label(self.root, textvariable=self.status_var).grid(row=5, column=0, columnspan=3, pady=5)
        
        ttk.Label(self.root, text="识别结果:").grid(row=6, column=0, padx=5, pady=5, sticky="nw")
        self.results_text = tk.Text(self.root, wrap=tk.WORD)
        self.results_text.grid(row=7, column=0, columnspan=3, padx=5, pady=5, sticky="nsew")
        
        self.root.grid_rowconfigure(7, weight=1)
        self.root.grid_columnconfigure(1, weight=1)
        
        scrollbar = ttk.Scrollbar(self.root, command=self.results_text.yview)
        scrollbar.grid(row=7, column=3, sticky="ns")
        self.results_text.config(yscrollcommand=scrollbar.set)
    
    def browse_input(self):
        directory = filedialog.askdirectory()
        if directory:
            self.input_dir.set(directory)
            if not self.output_dir.get():
                self.output_dir.set(os.path.join(directory, "renamed"))
    
    def browse_output(self):
        directory = filedialog.askdirectory()
        if directory:
            self.output_dir.set(directory)
    
    def process_images(self):
        input_dir = self.input_dir.get()
        output_dir = self.output_dir.get()
        
        if not input_dir:
            messagebox.showerror("错误", "请选择图片目录")
            return
            
        if not os.path.exists(input_dir):
            messagebox.showerror("错误", "图片目录不存在")
            return
            
        os.makedirs(output_dir, exist_ok=True)
        
        image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif')
        image_files = [f for f in os.listdir(input_dir) if f.lower().endswith(image_extensions)]
        
        if not image_files:
            messagebox.showwarning("警告", "目录中没有找到支持的图片")
            return
            
        self.results_text.delete(1.0, tk.END)
        total = len(image_files)
        success_count = 0
        
        for i, image_file in enumerate(image_files):
            self.status_var.set(f"正在处理: {image_file} ({i+1}/{total})")
            self.progress_var.set((i+1)/total*100)
            self.root.update()
            
            image_path = os.path.join(input_dir, image_file)
            original_ext = os.path.splitext(image_file)[1].lower()
            
            try:
                result = self.recognize_text_from_image(image_path)
                
                if 'words_result' in result and result['words_result']:
                    recognized_text = "".join([item['words'] for item in result['words_result']])
                    clean_text = re.sub(r'[\\/*?:"<>|]', "", recognized_text)
                    clean_text = clean_text.strip() or "未检测到文本"
                    
                    new_filename = f"{clean_text}{original_ext}"
                    output_path = os.path.join(output_dir, new_filename)
                    
                    counter = 1
                    while os.path.exists(output_path):
                        new_filename = f"{clean_text}_{counter}{original_ext}"
                        output_path = os.path.join(output_dir, new_filename)
                        counter += 1
                    
                    if self.preserve_original.get():
                        with Image.open(image_path) as img:
                            img.save(output_path)
                    else:
                        os.rename(image_path, output_path)
                    
                    self.results_text.insert(tk.END, f"原始文件: {image_file}\n新文件: {new_filename}\n识别结果: {recognized_text}\n\n")
                    success_count += 1
                else:
                    self.results_text.insert(tk.END, f"{image_file}: 未检测到文本\n\n")
            except Exception as e:
                self.results_text.insert(tk.END, f"{image_file} 处理失败: {str(e)}\n\n")
        
        self.status_var.set(f"完成! {success_count}/{total} 张图片已处理")
        messagebox.showinfo("完成", f"完成! {success_count}/{total} 张图片已处理")
    
    def recognize_text_from_image(self, image_path):
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token=" + self.get_access_token()
        image_base64 = self.get_file_content_as_base64(image_path, True)
        
        payload = f'image={image_base64}&detect_direction=false&probability=false&detect_alteration=false'
        headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
        
        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
        return response.json()
    
    def get_file_content_as_base64(self, path, urlencoded=False):
        with open(path, "rb") as f:
            content = base64.b64encode(f.read()).decode("utf8")
            if urlencoded:
                content = urllib.parse.quote_plus(content)
        return content
    
    def get_access_token(self):
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))

if __name__ == '__main__':
    root = tk.Tk()
    app = OCRApp(root)
    root.mainloop()